package com.live.shop.scene.server;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.live.shop.BaseActivity;
import com.live.shop.R;
import com.live.shop.aliyun.AliyunTtsUtil;
import com.live.shop.home.AudioFileListActivity;
import com.live.shop.home.setting.PermissionActivity;
import com.live.shop.model.AudioFileModel;
import com.live.shop.model.ProductGroupModel;
import com.live.shop.model.ProductMaterialRecordModel;
import com.live.shop.model.UserModel;
import com.live.shop.sql.ProductGroupListDatabase;
import com.live.shop.sql.UserDatabase;
import com.live.shop.tool.FileUtils;
import com.live.shop.tool.GetUtil;
import com.live.shop.tool.StatusBarUtils;
import com.live.shop.tool.TtsMessageEvent;
import com.live.shop.view.ToastBottomUtils;
import com.live.shop.view.ToastUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class AddMaterialActivity extends BaseActivity {
    ImageButton add_material_back;
    TextView add_material_title;
    EditText add_material_group_name;
    RecyclerView add_material_recyclerview;
    TextView add_material_add;
    TextView add_material_save;

    //播放器
    private MediaPlayer mediaPlayer;
    //录音
    private MediaRecorder mediaRecorder;
    UserModel userModel;
    private boolean isPlaying = false;//播放状态
    private int PlayingPosition = -1;//播放选择坐标
    //数据类型
    private int DataType = 0;
    //录音选择坐标
    private int sound_position = -1;
    private int activityResultType = 1;//1素材路径 2音频路径
    //录音状态
    private boolean sound_status = false;
    //是否已经开启Glide加载图片
    private boolean mAlreadyStart = true;

    private ProductGroupListDatabase groupDb;
    private UserDatabase userDb;
    private ProductGroupModel groupModel;
    private List<ProductMaterialRecordModel> list;
    private String fileDir="";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_material);
        StatusBarUtils.setDarkStatusWhite(this,R.color.white);
        //首先要在你要接受EventBus的界面注册，这一步很重要
        EventBus.getDefault().register(this);

        groupDb = new ProductGroupListDatabase(getApplicationContext());
        userDb = new UserDatabase(getApplicationContext());
        userModel = userDb.select();

        add_material_back = findViewById(R.id.add_material_back);
        add_material_title = findViewById(R.id.add_material_title);
        add_material_group_name = findViewById(R.id.add_material_group_name);
        add_material_recyclerview = findViewById(R.id.add_material_recyclerview);
        add_material_add = findViewById(R.id.add_material_add);
        add_material_save = findViewById(R.id.add_material_save);

        add_material_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        //添加
        add_material_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                list.add(new ProductMaterialRecordModel(true));
                adapter.notifyDataSetChanged();
            }
        });
        //保存
        add_material_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 移除当前Activity中所有视图的焦点，保证数据已存储
                clearFocusFromAllViews(findViewById(android.R.id.content));

                if(add_material_group_name.getText().toString().isEmpty()){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请填写产品组名称！");
                    return;
                }
                if(list.size() == 0){
                    ToastBottomUtils.Setinfo(getApplicationContext(),"请添加素材！");
                    return;
                }
                for (ProductMaterialRecordModel materialModel:list) {
                    //素材名称为空
                    if(materialModel.getMaterialName().isEmpty()) {
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请编辑素材名称！");
                        return;
                    }
                    //素材文件为空
                    if(materialModel.getMaterialFilepath().isEmpty()) {
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请选择素材文件！");
                        return;
                    }
                    //素材文件是否存在
                    if(!new File(materialModel.getMaterialFilepath()).exists()) {
                        ToastBottomUtils.Setinfo(getApplicationContext(),"素材名【"+materialModel.getMaterialName()+"】：素材文件不存在！");
                        return;
                    }
                    //如果设置了跟随回复 【要求：必须设置回复音频、关键词】
                    if(materialModel.getMaterialShowState() == 2) {
                        if(materialModel.getKeyword().isEmpty()) {ToastBottomUtils.Setinfo(getApplicationContext(),"跟随回复必须设置关键词！");return;}
                        if(materialModel.getAnswerState() == 0) {ToastBottomUtils.Setinfo(getApplicationContext(),"跟随回复必须设置回复音频！");return;}
                        if(!new File(materialModel.getAnswerAudio()).exists()) {
                            ToastBottomUtils.Setinfo(getApplicationContext(),"素材名【"+materialModel.getMaterialName()+"】：回复音频文件不存在！");
                            return;
                        }
                    }
                    //如果设置了自定义时间【要求：必须设置时间】
                    if(materialModel.getMaterialShowState() == 1) {
                        if(materialModel.getMaterialKeyShowtime() <= 0) {ToastBottomUtils.Setinfo(getApplicationContext(),"自定义时间必须填写秒数（正整数）");return;}
                    }
                }
                if(DataType == 0){
                    //新增
                    groupModel = new ProductGroupModel();
                    groupModel.setProductGroupName(add_material_group_name.getText().toString());
                    groupModel.setListRecord(list);
                    groupDb.insertData(groupModel);
                }else{
                    //编辑
                    groupModel.setProductGroupName(add_material_group_name.getText().toString());
                    groupModel.setListRecord(list);
                    groupDb.updateData(groupModel);
                }
                ToastUtils.Setinfo(getApplicationContext(),"保存成功",1);
                finish();
            }
        });

        add_material_recyclerview.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                switch (newState){
                    case RecyclerView.SCROLL_STATE_IDLE://滚动状态为空闲 0
                        startGlide(false);
                        break;
                    case RecyclerView.SCROLL_STATE_DRAGGING://滚动状态为拖拽 1
                        startGlide(true);
                        break;
                    case RecyclerView.SCROLL_STATE_SETTLING://滚动状态为自动滚动 2
                        startGlide(false);
                        break;
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        fileDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+"/zhiboMusic";
        File folder = new File(fileDir);
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                // 文件夹创建失败
                ToastUtils.Setinfo(getApplicationContext(),"无法创建文件夹！",2);
            }
        }
        SetListMyValue();
    }
    //加载数据
    private void SetListMyValue() {
        DataType = getIntent().getIntExtra("type",0);
        if(DataType == 1){
            groupModel = (ProductGroupModel) getIntent().getSerializableExtra("data");
            list = groupModel.getListRecord();
            add_material_title.setText("编辑产品组");
            add_material_group_name.setText(groupModel.getProductGroupName());
        }else{
            list = new ArrayList<>();
            list.add(new ProductMaterialRecordModel(true));
        }

        adapter = new MyAdapter();
        add_material_recyclerview.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
        add_material_recyclerview.setAdapter(adapter);
    }
    private MyAdapter adapter;
    class MyAdapter extends RecyclerView.Adapter {
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            RecyclerView.ViewHolder holder = new MyAdapter.MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.item_material, parent, false));
            return holder;
        }
        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, @SuppressLint("RecyclerView") int position) {
            MyAdapter.MyViewHolder mholder = (MyAdapter.MyViewHolder) holder;
            ProductMaterialRecordModel materialRecordModel = list.get(position);

            //第几个素材
            mholder.item_material_index.setText(String.valueOf(position+1));
            //素材名称
            mholder.item_material_name.setText(materialRecordModel.getMaterialName());

            //素材类型 0.图片 1.视频 2.文字
            List<TextView> materialTypeList = new ArrayList<>();
            materialTypeList.add(mholder.item_material_type_bgpicture);
            materialTypeList.add(mholder.item_material_type_bgvideo);
            GetUtil.setTextColor(getApplicationContext(),materialTypeList,materialRecordModel.getMaterialType());
            
            //素材隐藏状态 0 显示 1隐藏
            List<TextView> hideStateList = new ArrayList<>();
            hideStateList.add(mholder.item_material_hide_state_show);
            hideStateList.add(mholder.item_material_hide_state_hide);
            GetUtil.setTextColor(getApplicationContext(),hideStateList,materialRecordModel.getHideState());
            
            //展示时间状态  0长时间 1自义定  2跟随回复（必须设置关键词）
            List<TextView> materialShowStateList = new ArrayList<>();
            materialShowStateList.add(mholder.item_material_show_state_keep);
            materialShowStateList.add(mholder.item_material_show_state_custom);
            materialShowStateList.add(mholder.item_material_show_state_follow);
            GetUtil.setTextColor(getApplicationContext(),materialShowStateList,materialRecordModel.getMaterialShowState());
            
            //素材文件路径
            mholder.item_material_filepath_name.setText(materialRecordModel.getMaterialFilepath());

            if((materialRecordModel.getMaterialType() != 1)){
                //图片
                Glide.with(getApplicationContext())
                        .load(new File(materialRecordModel.getMaterialFilepath()))
                        .placeholder(R.mipmap.icon_image_square_default)
                        .into(new CustomTarget<Drawable>() {
                            @Override
                            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                mholder.item_material_filepath_check.setBackground(resource);
                            }
                            @Override
                            public void onLoadCleared(@Nullable Drawable placeholder) {

                            }
                        });
            }else{
                //视频
                try {
                    //引用形式的描述信息：获取视频文件的预览图
                    MediaMetadataRetriever retriever = new MediaMetadataRetriever();
                    retriever.setDataSource(materialRecordModel.getMaterialFilepath());
                    Glide.with(getApplicationContext())
                            .load(retriever.getFrameAtTime())
                            .placeholder(R.mipmap.icon_image_square_default)
                            .into(new CustomTarget<Drawable>() {
                                @Override
                                public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                                    mholder.item_material_filepath_check.setBackground(resource);
                                }
                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {

                                }
                            });
                    retriever.release();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            //自定义展示时间
            mholder.item_material_key_showtime.setText(String.valueOf(materialRecordModel.getMaterialKeyShowtime()));

            //展示时间状态
            if(materialRecordModel.getMaterialShowState() == 0){
                //0长时间 显示：【】隐藏：【自定义时间、关键词】
                mholder.item_material_key_showtime_linearLayout.setVisibility(View.GONE);
                mholder.item_material_answer_linearLayout.setVisibility(View.GONE);
            }else if(materialRecordModel.getMaterialShowState() == 1){
                //1自义定 显示：【自定义时间】【关键词】 隐藏：
                mholder.item_material_key_showtime_linearLayout.setVisibility(View.VISIBLE);
                mholder.item_material_answer_linearLayout.setVisibility(View.VISIBLE);
            }else{
                //2跟随回复 显示：【关键词】隐藏：【自定义时间】
                mholder.item_material_key_showtime_linearLayout.setVisibility(View.GONE);
                mholder.item_material_answer_linearLayout.setVisibility(View.VISIBLE);
            }

            //关键词
            mholder.item_material_answer_keyword.setText(materialRecordModel.getKeyword());
            mholder.item_material_answer_editText.setText(materialRecordModel.getAnswerTxt());
            mholder.item_material_answer_type.setText(GetUtil.voiceType(materialRecordModel.getAnswerType()));
            mholder.item_material_answer_status.setText(GetUtil.voiceState(materialRecordModel.getAnswerState()));
            //【试听】
            if(materialRecordModel.getAnswerState() != 0){
                //可点击和显示
                mholder.item_material_answer_sound_listen.setEnabled(true);
                mholder.item_material_answer_sound_listen.setVisibility(View.VISIBLE);
            }else{
                //不可点击和隐藏
                mholder.item_material_answer_sound_listen.setEnabled(false);
                mholder.item_material_answer_sound_listen.setVisibility(View.INVISIBLE);
            }
            //录音
            if(sound_status && sound_position == position){
                //【开始录音】不可点击和隐藏
                mholder.item_material_answer_sound_start.setEnabled(false);
                mholder.item_material_answer_sound_start.setVisibility(View.INVISIBLE);
                //【停止录音】可点击和显示
                mholder.item_material_answer_sound_stop.setEnabled(true);
                mholder.item_material_answer_sound_stop.setVisibility(View.VISIBLE);
            }else{
                //【开始录音】可点击和显示
                mholder.item_material_answer_sound_start.setEnabled(true);
                mholder.item_material_answer_sound_start.setVisibility(View.VISIBLE);
                //【停止录音】不可点击和隐藏
                mholder.item_material_answer_sound_stop.setEnabled(false);
                mholder.item_material_answer_sound_stop.setVisibility(View.INVISIBLE);
            }

            //【赋值】试听
            mholder.item_material_answer_sound_listen.setText(PlayingPosition == position?"停止试听":"试听");

            //删除
            mholder.item_material_delete.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    notifyItemRemoved(position);
                    groupDb.deleteRecordData(list.get(position).getId());
                    list.remove(position);

                    List<ProductMaterialRecordModel> demoList = new ArrayList<>();
                    for (ProductMaterialRecordModel m:list) {
                        demoList.add(m);
                    }
                    list.clear();
                    list.addAll(demoList);
                    notifyDataSetChanged();
                }
            });
            //素材名称
            mholder.item_material_name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // 处理焦点变化事件
                    if (!hasFocus) {
                        // EditText失去焦点时的处理逻辑
                        list.get(position).setMaterialName(mholder.item_material_name.getText().toString());
                    }
                }
            });
            //[素材类型]图片
            mholder.item_material_type_bgpicture.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(list.get(position).getMaterialType() != 0 && !list.get(position).getMaterialFilepath().isEmpty()){
                        //改变了类型，需要清空文件路径
                        list.get(position).setMaterialFilepath("");
                        list.get(position).setMaterialFileuri("");
                    }
                    list.get(position).setMaterialType(0);
                    notifyDataSetChanged();
                }
            });
            //[素材类型]视频
            mholder.item_material_type_bgvideo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(list.get(position).getMaterialType() != 1 && !list.get(position).getMaterialFilepath().isEmpty()){
                        //改变了类型，需要清空文件路径
                        list.get(position).setMaterialFilepath("");
                        list.get(position).setMaterialFileuri("");
                    }
                    list.get(position).setMaterialType(1);
                    notifyDataSetChanged();
                }
            });

            //点击素材查看
            mholder.item_material_filepath_check.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(!materialRecordModel.getMaterialFilepath().isEmpty()){
                        //new File(materialRecordModel.getMaterialFilepath()).exists()
                        //素材文件路径 不为空 且文件存在
                        Intent intent = new Intent(Intent.ACTION_VIEW);
                        if((materialRecordModel.getMaterialType() == 0 || materialRecordModel.getMaterialType() == 2)){
                            //图片
                            intent.setDataAndType(Uri.parse(materialRecordModel.getMaterialFileuri()), "image/*");
                        }else{
                            //视频
                            intent.setDataAndType(Uri.parse(materialRecordModel.getMaterialFileuri()), "video/*");
                        }
                        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);//注意加上这句话
                        startActivity(intent);
                    }else{
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请选择文件");
                    }
                }
            });
            //选择素材文件
            mholder.item_material_filepath_select.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    activityResultType = 1;//1素材路径 2音频路径
                    if(list.get(position).getMaterialType() == 0 || list.get(position).getMaterialType() == 2){
                        //图片
                        Matisse.from(AddMaterialActivity.this) //Activity
                                .choose(MimeType.ofImage()) //ofAll() -->全部类型   ofImage-->图片  ofVideo() -->视频
                                .countable(true)  // 有序选择图片
                                .maxSelectable(1)  //最大选择数量为9
                                .gridExpectedSize(400)  //图片显示表格的大小
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .showPreview(true) //是否预览
                                .thumbnailScale(0.85f)  //缩放比率
                                .imageEngine(new GlideEngine()) //加载方式
                                .forResult(position); //结果返回码 ，在onActivityResult 中获取requestCode
                    }else{
                        //视频
                        Matisse.from(AddMaterialActivity.this) //Activity
                                .choose(MimeType.ofVideo()) //ofAll() -->全部类型   ofImage-->图片  ofVideo() -->视频
                                .countable(true)  // 有序选择图片
                                .maxSelectable(1)  //最大选择数量为9
                                .gridExpectedSize(400)  //图片显示表格的大小
                                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                                .showPreview(true) //是否预览
                                .thumbnailScale(0.85f)  //缩放比率
                                .imageEngine(new GlideEngine()) //加载方式
                                .forResult(position); //结果返回码 ，在onActivityResult 中获取requestCode
                    }
                }
            });

            //[素材隐藏状态] 显示
            mholder.item_material_hide_state_show.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.get(position).setHideState(0);
                    notifyDataSetChanged();
                }
            });
            //[素材隐藏状态] 隐藏
            mholder.item_material_hide_state_hide.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.get(position).setHideState(1);
                    notifyDataSetChanged();
                }
            });

            //[展示时间状态]一直
            mholder.item_material_show_state_keep.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.get(position).setMaterialShowState(0);
                    notifyDataSetChanged();
                }
            });
            //[展示时间状态]自定义
            mholder.item_material_show_state_custom.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.get(position).setMaterialShowState(1);
                    notifyDataSetChanged();
                }
            });
            //[展示时间状态]跟随回复
            mholder.item_material_show_state_follow.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    list.get(position).setMaterialShowState(2);
                    notifyDataSetChanged();
                }
            });

            //自定义展示时间
            mholder.item_material_key_showtime.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // 处理焦点变化事件
                    if (!hasFocus) {
                        // EditText失去焦点时的处理逻辑
                        list.get(position).setMaterialKeyShowtime(Integer.valueOf(mholder.item_material_key_showtime.getText().toString()));
                    }
                }
            });
            //关键词
            mholder.item_material_answer_keyword.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // 处理焦点变化事件
                    if (!hasFocus) {
                        // EditText失去焦点时的处理逻辑
                        list.get(position).setKeyword(mholder.item_material_answer_keyword.getText().toString());
                    }
                }
            });
            //============================
            //回复文本编辑
            mholder.item_material_answer_editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View v, boolean hasFocus) {
                    // 处理焦点变化事件
                    if (!hasFocus) {
                        // EditText失去焦点时的处理逻辑
                        list.get(position).setAnswerTxt(mholder.item_material_answer_editText.getText().toString());
                    }
                }
            });
            //试听
            mholder.item_material_answer_sound_listen.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(!FileUtils.getFileExist(getApplicationContext(),materialRecordModel.getAnswerAudio())){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"音频文件不存在！");
                        return;
                    }
                    if(isPlaying){
                        //播放中，则取消播放
                        isPlaying = false;
                        mediaPlayer.stop();
                        mediaPlayer.release();
                        if(PlayingPosition == position){
                            //暂停
                            PlayingPosition = -1;
                            notifyDataSetChanged();
                            return;
                        }
                    }
                    if(PlayingPosition != position){
                        //开始播放
                        isPlaying = true;
                        PlayingPosition = position;
                        mediaPlayer = new MediaPlayer();
                        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
                        try {
                            mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(materialRecordModel.getAnswerAudio()));
                            mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                                @Override
                                public void onCompletion(MediaPlayer mediaPlayer) {
                                    mediaPlayer.release();
                                    isPlaying = false;
                                    PlayingPosition = -1;
                                    notifyDataSetChanged();
                                }
                            });
                            mediaPlayer.prepare();
                            mediaPlayer.start();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    notifyDataSetChanged();
                }
            });
            //开始录音
            mholder.item_material_answer_sound_start.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请到设置中授权【麦克风】权限！");
                        startActivity(new Intent(getApplicationContext(), PermissionActivity.class));
                        return;
                    }
                    //文件路径
                    String outputFile = fileDir+"/luyin_"+ DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";
                    mediaRecorder = new MediaRecorder();
                    mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
                    mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
                    mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
                    mediaRecorder.setOutputFile(outputFile);
                    try {
                        mediaRecorder.prepare();
                        mediaRecorder.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    //回答音频
                    list.get(position).setAnswerAudio(outputFile);
                    sound_position = position;
                    sound_status = true;
                    notifyDataSetChanged();
                }
            });
            //停止录音
            mholder.item_material_answer_sound_stop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if(mediaRecorder != null){
                        mediaRecorder.stop();
                        mediaRecorder.release();
                        mediaRecorder = null;
                    }
                    if(materialRecordModel.getAnswerType() != 0 && materialRecordModel.getAnswerType() != 3 && DataType == 1){
                        //编辑模型并且不是本地音频和无音频
                        list.get(position).setDeleteStatus(2);//删除状态 1新增 2编辑 3删除
                    }

                    //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                    list.get(position).setAnswerType(1);
                    //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                    list.get(position).setAnswerState(1);
                    sound_position = -1;
                    sound_status = false;

                    notifyDataSetChanged();
                }
            });
            //音频合成
            mholder.item_material_answer_sound_ai.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String answer = mholder.item_material_answer_editText.getText().toString();
                    if(answer.isEmpty()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请填写回复内容！");
                        return;
                    }
                    if(answer.length() > 300){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"回复内容超过300字符");
                        return;
                    }
                    list.get(position).setAnswerTxt(answer);

                    if(userModel.getAliyunAccessKeyID().isEmpty() || userModel.getAliyunAppkey().isEmpty() || userModel.getAliyunAccessKeySecret().isEmpty()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请先配置阿里云密钥！");
                        return;
                    }
                    if(userModel.getAliyunVoiceSelect().isEmpty() || userModel.getAliyunFontName().isEmpty()){
                        ToastBottomUtils.Setinfo(getApplicationContext(),"请选择保存阿里云音色！");
                        return;
                    }
                    //实例化tts
                    if(GetUtil.getUtf8CharsNum(answer) > 300){
                        ToastUtils.Setinfo(getApplicationContext(),"文本长度大于300字符",2);
                        return ;
                    }
                    //文件路径
                    String outputFile = fileDir+"/ai_"+DateFormat.format("yyyyMMdd_HHmmss", Calendar.getInstance(Locale.CHINA)) + ".mp3";

                    //语音合成
                    AliyunTtsUtil ttsUtil = new AliyunTtsUtil(userModel.getAliyunAppkey(),userModel.getAliyunAccessKeyID(),userModel.getAliyunAccessKeySecret());
                    //文本、保存文件名
                    ttsUtil.postRequest(getApplicationContext(),answer,outputFile);

                    if(materialRecordModel.getAnswerType() != 0 && materialRecordModel.getAnswerType() != 3 && DataType == 1){
                        //编辑模型并且不是本地音频和无音频
                        list.get(position).setDeleteStatus(2);//删除状态 1新增 2编辑 3删除
                    }
                    //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                    list.get(position).setAnswerType(2);
                    //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                    list.get(position).setAnswerState(2);
                    //回答音频
                    list.get(position).setAnswerAudio(outputFile);

                    notifyDataSetChanged();
                }
            });
            //选择本地音频
            mholder.item_material_answer_sound_local.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    activityResultType = 2;//1素材路径 2音频路径
                    Intent intent = new Intent(getApplicationContext(), AudioFileListActivity.class);
                    startActivityForResult(intent, position);
                }
            });

            mholder.itemView.setTag(this);
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public int getItemCount() {
            return list.size();
        }
        class MyViewHolder extends RecyclerView.ViewHolder {
            TextView item_material_index;
            ImageView item_material_delete;
            EditText item_material_name;
            TextView item_material_type_bgpicture;
            TextView item_material_type_bgvideo;
            TextView item_material_filepath_name;
            ImageView item_material_filepath_check;
            TextView item_material_filepath_select;
            TextView item_material_hide_state_show;
            TextView item_material_hide_state_hide;
            TextView item_material_show_state_keep;
            TextView item_material_show_state_custom;
            TextView item_material_show_state_follow;

            LinearLayout item_material_key_showtime_linearLayout;
            EditText item_material_key_showtime;

            LinearLayout item_material_answer_linearLayout;
            EditText item_material_answer_keyword;
            EditText item_material_answer_editText;
            TextView item_material_answer_type;
            TextView item_material_answer_status;
            TextView item_material_answer_sound_listen;
            TextView item_material_answer_sound_start;
            TextView item_material_answer_sound_stop;
            TextView item_material_answer_sound_ai;
            TextView item_material_answer_sound_local;
            public MyViewHolder( View itemView) {
                super(itemView);
                item_material_index = itemView.findViewById(R.id.item_material_index);
                item_material_delete = itemView.findViewById(R.id.item_material_delete);

                item_material_name = itemView.findViewById(R.id.item_material_name);
                item_material_type_bgpicture = itemView.findViewById(R.id.item_material_type_bgpicture);
                item_material_type_bgvideo = itemView.findViewById(R.id.item_material_type_bgvideo);
                item_material_filepath_name = itemView.findViewById(R.id.item_material_filepath_name);
                item_material_filepath_check = itemView.findViewById(R.id.item_material_filepath_check);
                item_material_filepath_select = itemView.findViewById(R.id.item_material_filepath_select);
                item_material_hide_state_show = itemView.findViewById(R.id.item_material_hide_state_show);
                item_material_hide_state_hide = itemView.findViewById(R.id.item_material_hide_state_hide);
                item_material_show_state_keep = itemView.findViewById(R.id.item_material_show_state_keep);
                item_material_show_state_custom = itemView.findViewById(R.id.item_material_show_state_custom);
                item_material_show_state_follow = itemView.findViewById(R.id.item_material_show_state_follow);

                item_material_key_showtime_linearLayout = itemView.findViewById(R.id.item_material_key_showtime_linearLayout);
                item_material_key_showtime = itemView.findViewById(R.id.item_material_key_showtime);

                item_material_answer_linearLayout = itemView.findViewById(R.id.item_material_answer_linearLayout);
                item_material_answer_keyword = itemView.findViewById(R.id.item_material_answer_keyword);
                item_material_answer_editText = itemView.findViewById(R.id.item_material_answer_editText);
                item_material_answer_type = itemView.findViewById(R.id.item_material_answer_type);
                item_material_answer_status = itemView.findViewById(R.id.item_material_answer_status);
                item_material_answer_sound_listen = itemView.findViewById(R.id.item_material_answer_sound_listen);
                item_material_answer_sound_start = itemView.findViewById(R.id.item_material_answer_sound_start);
                item_material_answer_sound_stop = itemView.findViewById(R.id.item_material_answer_sound_stop);
                item_material_answer_sound_ai = itemView.findViewById(R.id.item_material_answer_sound_ai);
                item_material_answer_sound_local = itemView.findViewById(R.id.item_material_answer_sound_local);
            }
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (data != null) {
                switch (activityResultType){
                    //activityResultType = 1;//1素材路径 2音频路径
                    case 1:
                        //图片路径 同样视频地址也是这个
                        List<String> stringList = Matisse.obtainPathResult(data);
//                        //Uri 格式的
                        List<Uri> uriList = Matisse.obtainResult(data);
                        //Log.d(GetUtil.TAG,"【String】"+stringList.get(0)+"，【Uri】"+uriList.get(0).toString());
                        // 【String】/storage/emulated/0/DCIM/Camera/IMG_20240324_092615.jpg，
                        // 【Uri.getPath()】/external/images/media/102932
                        // 【Uri.toString()】content://media/external/images/media/102932
                        list.get(requestCode).setMaterialFileuri(uriList.get(0).toString());
                        list.get(requestCode).setMaterialFilepath(stringList.get(0));
                        break;
                    case 2:
                        AudioFileModel audioModel = (AudioFileModel) data.getSerializableExtra("model");
                        list.get(requestCode).setAnswerAudio(audioModel.getUrl());
                        //合成方式 0.暂无 1.录音 2.AI合成 3.本地音频
                        list.get(requestCode).setAnswerType(3);
                        //合成状态 0.暂无 1.已录音 2.已合成 3.已选择
                        list.get(requestCode).setAnswerState(3);
                        break;
                }
                adapter.notifyDataSetChanged();
            }
        }
    }

    //任意写一个方法，给这个方法一个@Subscribe注解，参数类型可以自定义，但是一定要与你发出的类型相同
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(TtsMessageEvent messageEvent){
        switch (messageEvent.getNumber()) {
            case 1://正确
                ToastUtils.Setinfo(this,messageEvent.getMessage(),1);
                break;
            case 2://异常
                ToastUtils.Setinfo(this,messageEvent.getMessage(),2);
                break;
            case 3://底部toast
                ToastBottomUtils.Setinfo(this,messageEvent.getMessage());
                break;
        }
    }

    //暂停和重新开始 加载图片
    private void startGlide(boolean start) {
        if (mAlreadyStart) {
            if (start) {
                return;
            }
            mAlreadyStart = false;
            Glide.with(getApplicationContext()).pauseRequests();
        } else {
            if (!start) {
                return;
            }
            mAlreadyStart = true;
            Glide.with(getApplicationContext()).resumeRequests();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在界面销毁的地方要解绑
        EventBus.getDefault().unregister(this);
        // 释放MediaPlayer资源
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        // 释放mediaRecorder资源
        if (mediaRecorder != null) {
            mediaRecorder.release();
            mediaRecorder = null;
        }
    }
    private void clearFocusFromAllViews(ViewGroup root) {
        for (int i = 0; i < root.getChildCount(); i++) {
            View view = root.getChildAt(i);
            if (view instanceof ViewGroup) {
                clearFocusFromAllViews((ViewGroup) view);
            } else {
                view.clearFocus();
            }
        }
    }
}